﻿using Autofac.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Ongoal.Quotation.Middleware;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ongoal.Quotation.APIExtensions
{
    /// <summary>
    /// 
    /// </summary>
    public static class ApplicationExtensions
    {

        public const string HealthPath = "/Health/Check";
        /// <summary>
        /// 公共注入
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="configuration"></param>
        /// <param name="lifeTime"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseCommon(this IApplicationBuilder builder, IConfiguration configuration, IHostApplicationLifetime lifeTime)
        {

            builder.UseSwagger();
            builder.UseSwaggerUI();
            builder.UseCors(CommonExtensions.CorsPolicyName);
            builder.UseErrorHandler();
            builder.UseAuthorization();

            //服务发现注入
            builder.UseRegisterConsul(configuration, lifeTime);
            //分布式日志注入
            builder.UseExceptionless(configuration, lifeTime);


            builder.Map(HealthPath, (ap) =>
            {
                ap.Run(async httpc =>
                {
                    await httpc.Response.WriteAsJsonAsync(new { StatusCode = "200", Data = "OK", IsSucceed = true });
                });
            });

            return builder;
        }
        /// <summary>
        /// 公共开发环境注入
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseDev(this IApplicationBuilder builder, IConfiguration configuration)
        {


            return builder;
        }

        #region 使用错误处理中间件
        /// <summary>
        /// 使用错误处理中间件
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseErrorHandler(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ErrorHandlerMiddleware>();
        }
        #endregion
    }
}
